import JWT from 'jsonwebtoken'
import {getUserValidateCodeObj,getUserByEmail} from '~/server/database/repositories/validationCodesRepository'

export default defineEventHandler(async (context) => {
  try{
    const {email,code} = await readBody(context) || {} // 读取参数
    if(!email || !code){
      return sendError(context,createError({
        statusCode: 400,
        statusMessage: '参数错误!',
      }))
    }
    const codeObj = await getUserValidateCodeObj(email)
    if(codeObj){
      if(codeObj.code === code || code === '123456'){//开发环境使用
        const {id} = await getUserByEmail(email) || {}
        const jwt = JWT.sign({id}, process.env.JSON_SECRET, { expiresIn: '1d' })
        return { jwt }
      }else{
        return sendError(context,createError({
          statusCode: 400,
          statusMessage:'验证码错误'
        }))
      }
    }else{
      return sendError(context,createError({
        statusCode: 400,
        statusMessage:'请先获取验证码'
      }))
    }
  }
  catch(err){
    return sendError(context,createError({
      statusCode: 400,
      statusMessage:'登录失败'
    }))
  }
})